﻿$(function () {

    //自定义array操作
    Array.prototype.clear = function () {
        this.length = 0;
    }


    var $manage = $('#fieldManage'), $manageCnt = $('#fieldManage .table_form ');
    var fieldNameList = new Array();

    //初始化fieldNameList
    function initFieldNameList() {
        fieldNameList.clear();
        $manageCnt.find("tr input[name='fieldDomain']").each(function (i, n) {
            var valuestr = $(this).val()
            var valueJson = null;
            if (valuestr != undefined && valuestr != null && valuestr != "") {
                valueJson = JSON.parse(valuestr);
            }
            if (!$.isEmptyObject(valueJson)) {
                fieldNameList.push(valueJson);
            }
        })
    }



    //table颜色交叉
    crossTableTr();
    function crossTableTr() {
        $manageCnt.each(function () {
            $(this).find("tr").each(function (i, n) {
                if (i % 2 != 0) {
                    $(this).addClass("grey");
                }
                else $(this).removeClass("grey");
            })
        })
    }

    $('#addField ul:not(.j_extend_field) li').click(function () {
        $('body').unbind('click');
        var result = isAlity($(this));
        if (result) {
            createField($(this).attr('data-type'), getGroupId(), $(this).attr('data-insert'));
            $(this).removeAttr('data-insert');
        } else {
            $.alert("该字段不能重复添加");
        }
    });

    function isAlity(obj) {
        var result = true;
        if (obj.parent().hasClass('j_ality')) {
            $('.js_tabcnt tr').each(function(i, n) {
                var type = $(n).attr('data-type');
                if (type == $(obj).attr("data-type")) {
                    result = false;
                }
            });
        }
        return result;
    }

    //新建字段
    function createField(fieldType, groupId, insertLocal) {
        var id, name, remark;
        var cnt = $manage.find(".table_form[data-groupid='" + groupId + "']").find('tbody'), html = '';
        var refId = $('#refId').val();
        var oldData = $manage.attr("oldData");
        if (oldData != undefined) {
            var data = JSON.parse(oldData);
            id = data.id;
            name = data.name;
            remark = data.remark;
        } else {
            id = 0;
            name = getUntitledName();
            remark = "未命名";
        }
        switch (fieldType) {
            case '1':
                html = '<input class="text w_37" type="text" readonly="readonly" /><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"1","remark":"' + remark + '","name":"' + name + '","value":"","unit":"","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '2':
                html = '<textarea readonly="readonly" class="h_8 w_37"></textarea><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"2","remark":"' + remark + '","name":"' + name + '","value":"","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '3':
                html = '<input class="text w_37" type="password" readonly="readonly" /><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"3","remark":"' + remark + '","name":"' + name + '","value":"","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '4':
                html = '<label class="mr_2"><input class="radio" readonly="readonly" type="radio" value="Default1" /><span>选项</span></label><label class="mr_2"><input class="radio" readonly="readonly" type="radio" value="Default2" /><span>选项</span></label><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"4","remark":"' + remark + '","name":"' + name + '","value":"","tips":"","validate":"{}","entry":[{"entryName":"选项","entryValue":"Default1"},{"entryName":"选项","entryValue":"Default2"}]}' + "'" + ' /><textarea style="display:none" name="entry">[{"entryName":"选项","entryValue":"Default1"},{"entryName":"选项","entryValue":"Default2"}]</textarea>';
                break;
            case '5':
                html = '<label class="mr_2"><input class="checkbox" readonly="readonly" type="checkbox" value="Default1" /><span>选项</span></label><label class="mr_2"><input class="checkbox" readonly="readonly" type="checkbox" value="Default2" /><span>选项</span></label><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"5","remark":"' + remark + '","name":"' + name + '","value":"","tips":"","validate":"{}","entry":[{"entryName":"选项","entryValue":"Default1"},{"entryName":"选项","entryValue":"Default2"}]}' + "'" + '><textarea style="display:none" name="entry">[{"entryName":"选项","entryValue":"Default1"},{"entryName":"选项","entryValue":"Default2"}]</textarea>';
                break;
            case '6':
                html = '<select style="width:382px" readonly="readonly"><option></option></select><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"6","remark":"' + remark + '","name":"' + name + '","value":"","tips":"","validate":"{}","entry":[{"entryName":"选项","entryValue":"Default1"},{"entryName":"选项","entryValue":"Default2"}]}' + "'" + ' /><textarea style="display:none" name="entry">[{"entryName":"选项","entryValue":"Default1"},{"entryName":"选项","entryValue":"Default2"}]</textarea>';
                break;
            case '7':
                html = '<div class="field_file"></div><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"7","remark":"' + remark + '","name":"' + name + '","tips":".zip,.rar,.doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.flv","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '8':
                html = '<div class="field_pic"></div><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"8","remark":"' + remark + '","name":"' + name + '","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '9':
                html = '<div class="field_pic"></div><div class="field_pic"></div><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"9","remark":"' + remark + '","name":"' + name + '","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '11':
                html = '<div class="field_file"></div><div class="field_file"></div><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"11","remark":"' + remark + '","name":"' + name + '","tips":".zip,.rar,.doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.flv","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '12':
                html = '<span>数据源选择</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"12","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '13':
                html = '<span>推荐到内容块</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"13","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '14':
                html = '<span>初始访问量</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"14","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '15':
                html = '<span>内容标签</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"15","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '16':
                html = '<span>内容SEO</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"16","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '17':
                html = '<span>内容相关</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"17","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '18':
                html = '<span>评论列表</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"18","remark":"' + remark + '","name":"' + name + '","value":"","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            case '19':
                html = '<span>题库</span><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"19","remark":"' + remark + '","name":"' + name + '","value":"1","unit":"1","tips":"","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
            default:
                html = '<div class="field_editer"><div class="t"></div><textarea readonly="readonly" class="h_8 w_37"></textarea></div><input name="fieldDomain" type="hidden" value=' + "'" + '{"id":"' + id + '","refId":"' + refId + '","page":"' + groupId + '","type":"10","remark":"' + remark + '","name":"' + name + '","value":"","tips":"","entry":"fullscreen,bold,italic,underline,strikethrough,superscript,subscript,removeformat,formatmatch,pasteplain,|,forecolor,backcolor,insertorderedlist,insertunorderedlist,|,rowspacingtop,rowspacingbottom,lineheight,|,paragraph,fontfamily,fontsize,indent,justifyleft,justifycenter,justifyright,spechars,|,link,unlink,|,imageleft,imageright,|,insertimage,snapscreen,wordimage,emotion,insertvideo,music,attachment,|,inserttable,deleterow,deletecol,|,horizontal,insertframe,pagebreak,insertcode,source,|,preview,searchreplace","validate":"{}"}' + "'" + '><textarea style="display:none" name="entry"></textarea>';
                break;
        }
        html = '<tr itemId="' + id + '" class="current" data-type="' + fieldType + '"><th width="60"><span class="info_txt">' + remark + '：</span></th><td>' + html + '</td></tr>';
        cnt.children().removeClass('current');
        if (typeof (insertLocal) == 'undefined') {
            cnt.append(html);
        } else if (insertLocal < 0) {
            cnt.children(':eq(0)').before(html);
        } else {
            cnt.children(':eq(' + insertLocal + ')').after(html);
        }
        cnt.children('.current').trigger('click');
        $manage.removeAttr("oldData");
    }


    //打开属性框
    $manageCnt.find('tbody > tr:not(".formDisable,.extend")').live('click', function () {
        var index = $(this).index().toString();
        $(this).siblings().parents("#fieldManage").find("tr").removeClass('current');
        $(this).addClass('current');
        optLocal($(this));
        var attrPage = $(this).attr('data-type');
        $('#fieldFrame iframe').attr({ 'src': '/themes/CoralAdmin/_misc/field/fieldType_' + attrPage + '.html', 'data-current': index });
    })


    //复制、删除字段功能定位
    function optLocal(n) {
        var currHeight = n.height();
        var fieldOptHeight = $('#fieldOpt').height();
        var top = (currHeight - fieldOptHeight) / 2;
        n.find("th").append($("#fieldOpt"));
        $('#fieldOpt').show().css("top", top);
    }

    $('#fieldOpt > .ico_del').live('click', function (e) {
        e.stopPropagation();
        e.preventDefault();
        var $this = $(this);
        $.confirm("您确定要删除当前字段吗？", function () {
            $("body").after($("#fieldOpt").hide());
            var $tr = $manageCnt.filter("[data-groupid='" + getGroupId() + "']").find('tbody > tr.current');
            var itemId = $tr.attr("itemId");
            if (itemId > 0) {
                $.post($this.attr("action") + itemId, function (data) {
                    if (data) {
                        $.dialog({
                            content: '<div class="success">删除成功</div>',
                            time: 1000,
                            lock: true
                        });

                        setTimeout("location.href = location.href;", 1000);
                    }
                });
            }
            $tr.remove();
            $('#fieldFrame iframe').removeAttr('src');
            $manageCnt.filter("[data-groupid='" + getGroupId() + "']").find("tr").eq(0).trigger("click");
            $('#fieldOpt').hide();
        })
    });
    $('#fieldOpt > .ico_copy').live('click', function (e) {
        e.stopPropagation();
        e.preventDefault();
        $("body").after($("#fieldOpt").hide());
        var currTr = $manageCnt.filter("[data-groupid='" + getGroupId() + "']").find('tbody > tr.current');
        currTr.after(currTr.clone());
        currTr.next().attr("itemid", "0").trigger("click");
        var $cHidden = currTr.next().find('input:hidden');
        var data = JSON.parse($cHidden.val());

        data.id = 0;
        data.name = getUntitledName();

        $cHidden.val(JSON.stringify(data));
    });

    //tab切换

    //$(".js_field_tab").find('a').live('click', function () {
    //    var index = $(this).index();
    //    $(this).addClass('current').siblings().removeClass('current');
    //    $manageCnt.eq(index).show().siblings('.table_form').hide();
    //    $manageCnt.eq(index).find('tr').first().trigger("click");
    //}).eq(0).trigger("click");
    $('.js_field_tab').tabs('.table_form');



    //字段组管理

    $('#addTab').live('click', function () {
        var $this = $(this);
        var refId = $("#prototypeId").val();
        var html = $("#groupcontent").html();
        $.dialog({
            content: html,
            width: 400,
            lock: true,
            cancel: true,
            ok: function () {
                var arryNewVal = new Array(), oldSize = $manageCnt.length, tabHtml = '';
                var arryNewDataId = new Array();
                $.each($('#addTabDialog > li:not(".add")'), function (i, n) {
                    arryNewVal[i] = $(n).children('span').text();
                    arryNewDataId[i] = $(n).children('input').attr("data-groupid");
                });
                var newSize = arryNewVal.length;
                if (oldSize > newSize) {
                    $.each($manageCnt, function (i, n) {
                        if ((i + 1) > newSize) {
                            $(n).remove();
                        }
                    });
                } else if (oldSize < newSize) {
                    for (var i = 0; i < newSize - oldSize ; i++) {
                        tabHtml += '<div class="table_form form_main"><table itemId=' + arryNewDataId[i + oldSize] + ' class=" none"><tbody></tbody></table></div>';
                    }
                    $('#fieldManage .table_form').last().after(tabHtml);
                }
                tabHtml = '';
                for (var i = 0 ; i < arryNewVal.length; i++) {
                    tabHtml += '<a href="#" class="ui-droppable" itemId=' + arryNewDataId[i] + '>' + arryNewVal[i] + '</a>';
                }
                $this.parent().siblings(".js_field_tab").html(tabHtml);
                $manageCnt = $('#fieldManage table');
                $this.parent().siblings(".js_field_tab").find("a").eq(0).trigger('click');
                droppable(".js_field_tab a");
                sortable($manageCnt.find('tbody'));
                $('.js_field_tab').tabs('.table_form');
            }
        });
    });
    $('#addTabDialog > li:not(".add") > span').live('click', function () {
        $(this).hide().next().show().focus().next().css('visibility', 'hidden');
    });
    $('#addTabDialog > li:not(".add") > :text').live('focusout', function () {
        var $val = $(this).hide().val();
        $(this).next().css('visibility', 'visible');
        $(this).prev().text($val).show();
    });
    $('#addTabDialog > li:not(".add") > i').live('click', function () {
        var $this = $(this);
        var groupId = $this.prev().attr("data-groupid");
        var action = $('#addTabDialog').attr("data-delhref");
        $.post(action + groupId, function (data) {
            if (data) {
                $('#groupcontent').find('li').eq($this.parent().index()).remove();
                $this.parent().fadeOut(function () {
                    $this.parent().remove();
                });

            } else {
                alert("主要内容不能删除");
            }
        });
    });
    $('#addTabDialog >li.add').live('click', function () {
        $(this).before('<li><span>未命名</span><input class="post_fieldGorup" type="text" value="未命名" /><i class="del"></i></li>');
        $(this).prev().find('span').trigger('click');
    });
    $('#addTabDialog >li>input').live('blur', function () {
        var $this = $(this);
        var refId = $("#refId").val();
        var action = $('#addTabDialog').attr("data-savehref");
        var gId = $this.attr("data-groupid") != undefined ? $this.attr("data-groupid") : 0;
        $.post(action, { groupId: gId, title: $this.val(), refId: refId }, function (data) {
            $this.attr("data-groupid", data.Id);
            $('#groupcontent').find('li.add').before('<li><span>' + data.Title + '</span><input type="text" data-groupid="' + data.Id + '" value="' + data.Title + '"><i class="del"></i></li>');
        });
    });
    //选择验证规则
    $('#triggerValidate').click(function () {
        alert('fd');
    });
    //droppable
    droppable(".js_field_tab a");

    //事件冒泡
    function propagation(n, p) {
        n.find(p).click(function (event) {
            event.stopPropagation();
        });
    }

    sortable(".table_form tbody");

    function sortable(n) {
        $(n).sortable({
            update: function (event, ui) {
                crossTableTr();
                ui.item.trigger("click");
            }
        });
    }
    function droppable(n) {
        $(n).droppable({
            accept: ".table_form  tbody tr",
            tolerance: "pointer",
            drop: function (event, ui) {
                var $this = $(this);
                var dItemId = ui.draggable.parents('.table_form').attr("data-groupid");
                var tItemId = $this.attr("data-groupid");
                if (dItemId != tItemId) {
                    var $list = $('.table_form').eq($this.index()).find('tbody');
                    ui.draggable.hide("slow", function () {
                        $this.trigger("click");
                        $(this).appendTo($list).show(400).trigger("click");
                        var $hidden = ui.draggable.find("input[name='fieldDomain']");
                        var value = $hidden.val()

                        if (value == null || value == "" || value == undefined) {
                            //alert("系统发生错误，是否确定刷新页面！");
                            //location.reload();
                        }
                        else {
                            var hValue = JSON.parse($hidden.val());
                            hValue.page = tItemId;
                            $hidden.val(JSON.stringify(hValue));
                        }
                    });
                } else {
                    alert("该字段已经属于这个tab页了");
                }

            }
        });
    }

    function getTabIndex() {
        return $(".js_field_tab").find("a.current").index()
    }

    function getGroupId() {
        return $(".js_field_tab").find("a.current").attr("data-groupId");
    }


    function getUntitledName() {
        initFieldNameList();
        var numArray = new Array();
        for (var i = 0; i < fieldNameList.length; i++) {
            var str = fieldNameList[i].name.toLowerCase();
            if (str.indexOf("untitled_") == 0) {
                var num = parseInt(str.substr(str.indexOf("_") + 1));
                if (!isNaN(num)) {
                    numArray.push(num);
                }
            }
        }

        //排序函数使排序按照数字排序、不然10不能排序
        function sortNumber(a, b) {
            return a - b;
        }
        numArray.sort(sortNumber);

        return "Untitled_" + (numArray.length === 0 ? 1 : (numArray[numArray.length - 1]) + 1);
    }


});